import { memo, useEffect, useState } from "react"
import { allRoutes } from "@/router";
import { Link, useLocation, useNavigate } from "react-router-dom";
import type { IRouter } from "@/types/router";
import { resolve } from "@/Utils/path";
import { Avatar, Dropdown } from "antd";
import type { MenuProps } from "antd";
import { SearchComponent } from "@/components/Search";

const Header = memo(() => {
  const navigate = useNavigate();
  const location = useLocation();
  const [activePath, setActivePath] = useState('');
  useEffect(() => {
    setActivePath('/' + location.pathname.split('/')[1]);
  }, [location]);

  // 渲染子菜单项
  const renderSubMenuItems = (children: IRouter[], parentPath: string): MenuProps['items'] => {
    return children.filter(child => child.meta && !child.meta.hidden).map(child => ({
      key: resolve(parentPath, child.path),
      label: (
        <div
          style={{ display: 'flex', alignItems: 'center' }}
          onMouseEnter={(e) => {
            e.currentTarget.style.color = 'blue'
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.color = ''
          }}
        >
          {child.meta.title}
        </div>
      ),
      onClick: () => navigate(resolve(parentPath, child.path))
    }));
  };

  // 渲染一级菜单
  const renderMenuItems = (menu: IRouter[], parentPath = '') => {
    return menu.map((item) => {
      const { children, meta, path } = item;
      if (meta?.hidden === true) {
        // hidden == true，不渲染
        return null;
      }

      // 获取菜单的meta信息
      const { title } = meta;
      const routerPath = resolve(parentPath, path);

      // 没有子路由 直接渲染
      if (!children || children.length === 0) {
        return (
          <Link
            key={routerPath}
            to={routerPath}
            className={`px-2 py-1 my-2 transition-colors duration-300 hover:text-blue-600 ${activePath === routerPath ? 'text-blue-600 font-bold' : 'text-gray-600'
              }`}
            onClick={() => {
              setActivePath(routerPath)
            }}
          >
            {title}
          </Link>
        );
      }
      // 有子路由 渲染下拉菜单
      return (
        <Dropdown
          key={routerPath}
          menu={{
            items: renderSubMenuItems(children, routerPath)
          }}
          placement="bottom"
        >
          <div
            className={`px-2 py-1 my-1 transition-colors duration-300 hover:text-blue-600 ${activePath === routerPath ? 'text-blue-600 font-bold' : 'text-gray-600'
              }`}
          >
            {title}
          </div>
        </Dropdown>
      );
    }).filter(Boolean);
  };

  return (
    <header id="obRoot" className="sticky top-0 left-0 right-0 z-50 bg-white " style={{ boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.05)' }}>
      <div className="m-auto py-2 px-6" style={{ maxWidth: '90rem' }}>
        <div className="flex items-center justify-between">
          <div className="text-xl font-bold mr-8" onClick={() => navigate('/')}>前端技术社区</div>
          <nav className="flex items-center gap-4" style={{ flex: '1 1 0%' }}>
            {renderMenuItems(allRoutes)}
          </nav>
          <div className="flex justify-between gap-4">
            <div className="relative">
              <SearchComponent />
            </div>

            {/* 用户信息 */}
            <div className="flex items-center gap-2">
              <Avatar size={30} src="https://api.dicebear.com/7.x/avataaars/svg?seed=1"></Avatar>
            </div>
          </div>

        </div>
      </div>
    </header>
  )
})

Header.displayName = 'Header';

export default Header;